package znet

import (
	"bytes"
	"encoding/binary"
	"errors"
	"zinxp/utils"
	"zinxp/ziface"
)

//封包拆包实例，暂时不需要成员
type DataPack struct {
}

func NewDataPack() *DataPack {
	return &DataPack{}
}

func (dp *DataPack) GetHeadLen() uint32 {
	// ID uint32 + DataLen uint32 = 8
	return 8
}

func (dp *DataPack) Pack(msg ziface.IMessage) ([]byte, error) {
	//创建一个存放字节的缓冲
	databuf := bytes.NewBuffer([]byte{})

	//写datalen
	if err := binary.Write(databuf, binary.LittleEndian, msg.GetDataLen()); err != nil {
		return nil, err
	}
	//写msgID
	if err := binary.Write(databuf, binary.LittleEndian, msg.GetMsgId()); err != nil {
		return nil, err
	}
	//写数据data
	if err := binary.Write(databuf, binary.LittleEndian, msg.GetData()); err != nil {
		return nil, err
	}
	return databuf.Bytes(), nil
}

func (dp *DataPack) Unpack(binaryData []byte) (ziface.IMessage, error) {
	databuf := bytes.NewReader(binaryData)

	//只解压head信息，得到len和msgID
	msg := &Message{}
	if err := binary.Read(databuf, binary.LittleEndian, &msg.DataLen); err != nil {
		return nil, err
	}
	if err := binary.Read(databuf, binary.LittleEndian, &msg.Id); err != nil {
		return nil, err
	}
	//if err := binary.Read(databuf, binary.LittleEndian, &msg.Data); err != nil {
	//	return nil, err
	//}
	//判断dataLen的长度是否超出我们允许的最大包长度
	if utils.GlobalObject.MaxPacketSize >0 && msg.DataLen > utils.GlobalObject.MaxPacketSize{
		return nil,errors.New("Too large msg data recived")
	}
	//这里只需要把head的数据拆包出来就可以了，然后再通过head的长度，再从conn读取一次数据
	return msg, nil
}
